package com.unittec.drainage.provider.auth.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.unittec.drainage.provider.auth.dto.SysDepartTree;
import com.unittec.drainage.provider.auth.entity.SysDepart;
import com.unittec.drainage.provider.auth.service.SysDepartService;
import com.unittec.drainage.provider.auth.service.SysRoleService;
import com.unittec.drainage.provider.auth.service.SysUserRoleService;
import com.unittec.drainage.provider.common.BeanValidator;
import com.unittec.drainage.provider.log.Log;
import com.unittec.drainage.provider.utils.CopyListUtils;
import com.unittec.drainage.provider.utils.ValidationUtils;
import com.unittec.drainage.sdk.auth.domain.SysDepartDto;
import com.unittec.drainage.sdk.auth.request.*;
import com.unittec.drainage.sdk.auth.response.*;
import com.unittec.drainage.sdk.log.enums.LogOperateEnum;
import com.unittec.drainage.sdk.log.enums.LogStatusEnum;
import com.unittec.drainage.sdk.root.common.CommonConstant;
import com.unittec.drainage.sdk.root.domain.GatewayRequest;
import com.unittec.drainage.sdk.root.domain.Result;
import com.unittec.drainage.sdk.root.enums.BizCode;
import com.unittec.drainage.sdk.root.enums.BizCodeEnum;
import com.unittec.drainage.sdk.root.internal.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author chengjie
 * @description 部门管理
 * @date 2019/10/21
 */
@RestController
@Api(tags = "部门管理")
public class SysDepartController {

    @Resource
    Log log;

    @Resource
    private SysDepartService sysDepartService;

    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysRoleService sysRoleService;

    @RequestMapping(value = "/101400", method = RequestMethod.POST)
    @ApiOperation(value = "查询所有部门", notes = "查询所有部门")
    @ResponseBody
    public Result<Res101400> queryTreeList(@RequestBody GatewayRequest<Req101400> req) {
        log.debug(req, "queryTreeList {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101400 res101400 = null;
        try {
            List<SysDepartTree> list = sysDepartService.queryTreeList(req.getContent().getContainUserFlag());
            res101400 = new Res101400();
            res101400.setList(list);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "queryTreeList {}  ", "end");
        if (bizCodeEnum.getCode().equalsIgnoreCase(BizCode.SUCCESS.getCode())) {
            return Result.success(req, res101400);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101401", method = RequestMethod.POST)
    @ApiOperation(value = "根据条件查询部门", notes = "根据条件查询部门")
    @ResponseBody
    public Result<Res101401> searhBy(@RequestBody GatewayRequest<Req101401> req) {
        log.debug(req, "searhBy {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101401 res101401 = null;
        try {
            List<SysDepartTree> list = sysDepartService.searhBy(req.getContent().getDepartName());
            res101401 = new Res101401();
            res101401.setList(list);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "searhBy {}  ", "end");
        if (bizCodeEnum.getCode().equalsIgnoreCase(BizCode.SUCCESS.getCode())) {
            return Result.success(req, res101401);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101402", method = RequestMethod.POST)
    @ApiOperation(value = "添加部门", notes = "添加部门")
    @ResponseBody
    public Result<Res101402> addDepart(@RequestBody GatewayRequest<Req101402> req) {
        log.debug(req, "addDepart {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101402 res101402 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            SysDepart sysDepart = new SysDepart();
            BeanUtils.copyProperties(req.getContent(), sysDepart);
            initDepartLevel(sysDepart);
            sysDepartService.saveDepartData(sysDepart);
            res101402 = new Res101402();
            res101402.setIsSuccess(true);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101402", JSON.toJSONString(req), "添加部门", log.buildErrmsg(e),
                    LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "addDepart {}  ", "end");
        if (bizCodeEnum.getCode().equalsIgnoreCase(BizCode.SUCCESS.getCode())) {
            log.addOperateLog("101402", JSON.toJSONString(req), "添加部门", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101402);
        } else {
            log.addOperateLog("101402", JSON.toJSONString(req), "添加部门", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_ADD.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101403", method = RequestMethod.POST)
    @ApiOperation(value = "修改部门", notes = "修改部门")
    @ResponseBody
    public Result<Res101403> updateDepart(@RequestBody GatewayRequest<Req101403> req) {
        log.debug(req, "updateDepart {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101403 res101403 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            String id = req.getContent().getId();
            SysDepart sysDepart = sysDepartService.getById(id);
            if (sysDepart != null) {
                BeanUtils.copyProperties(req.getContent(), sysDepart);

                //初始化部门层级
                initDepartLevel(sysDepart);
                //递归修改部门层级
                recursionUpdateDepart(sysDepart);
                boolean ok = sysDepartService.updateById(sysDepart);
                if (ok) {
                    res101403 = new Res101403();
                    res101403.setIsSuccess(true);
                    bizCodeEnum = BizCode.SUCCESS;
                }
            } else {
                bizCodeEnum = BizCode.NOT_DEPART;
            }
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101403", JSON.toJSONString(req), "修改部门", log.buildErrmsg(e),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "updateDepart {}  ", "end");
        if (bizCodeEnum == BizCode.SUCCESS) {
            log.addOperateLog("101403", JSON.toJSONString(req), "修改部门", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101403);
        } else {
            log.addOperateLog("101403", JSON.toJSONString(req), "修改部门", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_UPDATE.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }


    /**
     * 递归修改子部门层级
     *
     * @param sysDepart
     */
    private void recursionUpdateDepart(SysDepart sysDepart) {
        LambdaQueryWrapper<SysDepart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysDepart::getParentId, sysDepart.getId());
        List<SysDepart> list = sysDepartService.list(lambdaQueryWrapper);
        if (list != null && list.size() > 0) {
            for (SysDepart dto : list) {
                SysDepart updateDto = new SysDepart();
                updateDto.setId(dto.getId());
                updateDto.setDepartLevel(sysDepart.getDepartLevel());
                sysDepartService.updateById(updateDto);
                recursionUpdateDepart(dto);
            }
        }
    }

    /**
     * 递归获取部门相关信息
     *
     * @param id
     * @param list
     */
    private void recursionDepartList(String id, List<SysDepart> list) {
        if (list == null) {
            list = new ArrayList<>();
        }
        LambdaQueryWrapper<SysDepart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysDepart::getParentId, id);
        lambdaQueryWrapper.eq(SysDepart::getDelFlag, CommonConstant.DELETE_NO);
        List<SysDepart> subList = sysDepartService.list(lambdaQueryWrapper);
        list.addAll(subList);
        if (subList.size() > 0) {
            for (SysDepart dto : list) {
                recursionDepartList(dto.getId(), list);
            }
        }
    }


    /**
     * 设置部门层级
     *
     * @param sysDepart
     */
    private void initDepartLevel(SysDepart sysDepart) {
        if (StringUtils.isNotBlank(sysDepart.getParentId())) {
            SysDepart parentDepart = sysDepartService.getById(sysDepart.getParentId());
            if (parentDepart == null) {
                throw new BusinessException("未查询到父部门信息");
            }
            int level = parentDepart.getDepartLevel() == null ? 0 : parentDepart.getDepartLevel();
            sysDepart.setDepartLevel(level + 1);
        } else {
            sysDepart.setDepartLevel(0);
        }
    }

    @RequestMapping(value = "/101404", method = RequestMethod.POST)
    @ApiOperation(value = "批量删除部门", notes = "批量删除部门")
    @ResponseBody
    public Result<Res101404> deleteBatch(@RequestBody GatewayRequest<Req101404> req) {
        log.debug(req, "deleteBatch {}  ", "begin");
        long startLogTime = System.currentTimeMillis();
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101404 res101404 = null;
        try {
            ValidationUtils.validateEntityStr(req.getContent());
            String ids = req.getContent().getIds();
            sysDepartService.deleteBatchWithChildren(Arrays.asList(ids.split(",")));
            res101404 = new Res101404();
            res101404.setIsSuccess(true);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            log.addOperateLog("101404", JSON.toJSONString(req), "批量删除部门", log.buildErrmsg(e),
                    LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "deleteBatch {}  ", "end");
        if (bizCodeEnum.getCode().equalsIgnoreCase(BizCode.SUCCESS.getCode())) {
            log.addOperateLog("101404", JSON.toJSONString(req), "批量删除部门", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.SUCCESS.getCode(), startLogTime);
            return Result.success(req, res101404);
        } else {
            log.addOperateLog("101404", JSON.toJSONString(req), "批量删除部门", bizCodeEnum.getMessage(),
                    LogOperateEnum.LOG_DEL.getCode(), LogStatusEnum.ERROR.getCode(), startLogTime);
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101405", method = RequestMethod.POST)
    @ApiOperation(value = "查询所有部门及用户", notes = "查询所有部门及用户")
    @ResponseBody
    public Result<Res101405> queryAllDepartAndUser(@RequestBody GatewayRequest<Req101405> req) {
        log.debug(req, "queryAllDepartAndUser {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101405 res101405 = null;
        try {
            List<SysDepartTree> list = sysDepartService.queryAllDepartAndUser();
            res101405 = new Res101405();
            res101405.setList(list);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "queryTreeList {}  ", "end");
        if (bizCodeEnum.getCode().equalsIgnoreCase(BizCode.SUCCESS.getCode())) {
            return Result.success(req, res101405);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }

    @RequestMapping(value = "/101406", method = RequestMethod.POST)
    @ApiOperation(value = "根据父级Id查询所有部门及用户", notes = "根据父级Id查询所有部门及用户")
    @ResponseBody
    public Result<Res101406> findDepartUserTree(@RequestBody GatewayRequest<Req101406> req) {
        log.debug(req, "findDepartUserTree {}  ", "begin");
        BizCodeEnum bizCodeEnum = BizCode.ERROR;
        Res101406 res101406 = null;
        try {
            List<Map<String, Object>> list = sysDepartService.findDepartUserTree(req.getContent().getParentId());
            res101406 = new Res101406();
            res101406.setList(list);
            bizCodeEnum = BizCode.SUCCESS;
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
        log.debug(req, "findDepartUserTree {}  ", "end");
        if (bizCodeEnum.getCode().equalsIgnoreCase(BizCode.SUCCESS.getCode())) {
            return Result.success(req, res101406);
        } else {
            return Result.error(req, bizCodeEnum);
        }
    }


    @RequestMapping(value = "/101407", method = RequestMethod.POST)
    @ApiOperation(value = "根据用户ID查询该用户的部门", notes = "根据用户ID查询该用户的部门")
    @ResponseBody
    public Result<Res101407> findDepartIdsByUserId(@RequestBody GatewayRequest<Req101407> req) {
        log.debug(req, "findDepartIdsByUserId {}  ", "begin");
        Res101407 res101407 = null;
        try {
            String userId = req.getContent().getUserId();
            boolean recursionStatus = req.getContent().getRecursionStatus() == null ? false : req.getContent().getRecursionStatus();
            List<String> list = sysDepartService.findDepartIdsByUserId(userId, recursionStatus);
            res101407 = new Res101407();
            res101407.setDepartList(list);
            log.debug(req, "findDepartIdsByUserId {}  ", "end");
            return Result.success(req, res101407);
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
    }


    @RequestMapping(value = "/101408", method = RequestMethod.POST)
    @ApiOperation(value = "根据部门ID查询部门", notes = "根据部门ID查询部门")
    @ResponseBody
    public Result<Res101408> findDepartInfoById(@RequestBody GatewayRequest<Req101408> req) {
        log.debug(req, "findDepartInfoById {}  ", "begin");
        Res101408 res101408 = new Res101408();
        try {
            BeanValidator.validate(req.getContent());
            List<String> ids = req.getContent().getIds();
            List<SysDepart> departs = sysDepartService.listByIds(ids);
            List<SysDepartDto> list = CopyListUtils.copyList(departs, SysDepartDto.class);
            res101408.setList(list);
            log.debug(req, "findDepartInfoById {}  ", "end");
            return Result.success(req, res101408);
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
    }


    @RequestMapping(value = "/101409", method = RequestMethod.POST)
    @ApiOperation(value = "根据部门父ID查询部门数结构", notes = "根据部门父ID查询部门数结构")
    @ResponseBody
    public Result<Res101409> findDepartInfoParentId(@RequestBody GatewayRequest<Req101409> req) {
        log.debug(req, "findDepartInfoParentId {}  ", "begin");
        Res101409 res101409 = new Res101409();
        try {
            BeanValidator.validate(req.getContent());
            Req101409 req101409 = req.getContent();
            res101409.setList(sysDepartService.findDepartInfoParentId(req101409.getParentId(), req101409.getRecursion(), req101409.getSelfStatus()));
            log.debug(req, "findDepartInfoParentId {}  ", "end");
            return Result.success(req, res101409);
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
    }

    @RequestMapping(value = "/101410", method = RequestMethod.POST)
    @ApiOperation(value = "查询所有部门", notes = "查询所有部门")
    @ResponseBody
    public Result<Res101410> findAllDept(@RequestBody GatewayRequest<Req101410> req) {
        log.debug(req, "findAllDept {}  ", "begin");
        Res101410 res101410 = new Res101410();
        try {
            BeanValidator.validate(req.getContent());
            List<SysDepart> list = sysDepartService.list();
            res101410.setList(CopyListUtils.copyList(list, SysDepartDto.class));
            log.debug(req, "findAllDept {}  ", "end");
            return Result.success(req, res101410);
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
    }

    @RequestMapping(value = "/101411", method = RequestMethod.POST)
    @ApiOperation(value = "根据用户id查询所属部门名称", notes = "根据用户id查询所属部门名称")
    @ResponseBody
    public Result<Res101411> getDeptNameByUserId(@RequestBody GatewayRequest<Req101411> req) {
        log.debug(req, "getDeptNameByUserId {}  ", "begin");
        Res101411 res101411 = new Res101411();
        try {
            BeanValidator.validate(req.getContent());

            String deptName = sysDepartService.getMapper().getDeptNameByUserId(req.getContent().getUserId());

            res101411.setDeptName(deptName);
            log.debug(req, "getDeptNameByUserId {}  ", "end");
            return Result.success(req, res101411);
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
    }


    @RequestMapping(value = "/101412", method = RequestMethod.POST)
    @ApiOperation(value = "根据用户id查询所属部门名称", notes = "根据用户id查询所属部门名称")
    @ResponseBody
    public Result<Res101412> getDeptNameByUserIds(@RequestBody GatewayRequest<Req101412> req) {
        log.debug(req, "getDeptNameByUserIds {}  ", "begin");
        Res101412 res101412 = new Res101412();
        try {
            BeanValidator.validate(req.getContent());

            List<Map<String, Object>> list = sysDepartService.getMapper().getDeptNameByUserIds(req.getContent().getUserIds());
            res101412.setUserDepartMap(list);
            log.debug(req, "getDeptNameByUserIds {}  ", "end");
            return Result.success(req, res101412);
        } catch (Exception e) {
            log.error(req, e.toString(), e);
            return Result.error(req, e.getMessage());
        }
    }

}
